using System.IO;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Notifications;
using Avalonia.Controls.Primitives;
using Avalonia.Threading;
using FluentAvalonia.UI.Windowing;
using LiveHub.AvaloniaApp.Pages;
using LiveHub.AvaloniaApp.ViewModels.Pages;
using LiveHub.DataModels;
using Newtonsoft.Json;

namespace LiveHub.AvaloniaApp.Views;

public partial class MainWindow : AppWindow
{
    public string Jwt { get; private set; } = "";
    private WindowNotificationManager? _manager;
    private UserModel User { get; set; }

    public MainWindow(UserModel user)
    {
        User = user;
        InitializeComponent();
        SplashScreen = new MainAppSplashScreen("LiveHub", InitApp);
        TitleBar.ExtendsContentIntoTitleBar = true;
        TitleBar.TitleBarHitTestType = TitleBarHitTestType.Complex;
    }

    private async void InitApp()
    {
        using UserHttp http = new();
        if (!string.IsNullOrEmpty(User.UserId))
        {
            Jwt = await http.Login(new LoginModel() { Name = User.UserName, Id = User.UserId });
        }

        if (string.IsNullOrEmpty(Jwt))
        {
            Dispatcher.UIThread.Post(() => ChangeItem(new LoginView()));
        }
        else
        {
            User = await http.GetData() ?? User;
            if (string.IsNullOrEmpty(User.Gender)) return;
            User.Groups = await http.GetUserGroups();
            DataInit();
        }
    }

    private bool DataInit()
    {
        Dispatcher.UIThread.Post(() =>
        {
            var main = new MainView(Jwt,User);
            var setting = new SettingViewModel() { User = User };

            main.Stack["Setting"] = setting;
            ChangeItem(main);
            main.NavigateFirstChat();
        });
        return true;
    }

    public async Task<bool> Login(LoginModel model)
    {
        using UserHttp http = new();
        var jwt = await http.Login(model);
        if (string.IsNullOrEmpty(jwt)) return false;
        Jwt = jwt;
        User = await http.GetData() ?? User;
        if (string.IsNullOrEmpty(User.Gender)) return false;
        User.Groups = await http.GetUserGroups();
        var b = DataInit();
        await File.WriteAllTextAsync("data.json", JsonConvert.SerializeObject(User));
        return b;
    }

    protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
    {
        base.OnApplyTemplate(e);
        _manager = new WindowNotificationManager(this) { MaxItems = 3, Position = NotificationPosition.BottomRight };
    }

    public void NotificationShow(string title, string message, NotificationType type = NotificationType.Information)
    {
        _manager?.Show(new Notification(title, message, type));
    }

    public void ChangeItem(Control control)
    {
        if(Grid.Children.Count > 1)
            Grid.Children.RemoveAt(1);
        Grid.SetRow(control, 1);
        Grid.Children.Add(control);
    }

    public async Task Copy(string text,string? title = null,string? message = null)
    {
        if(Clipboard == null)return;
        await Clipboard.SetTextAsync(text);
        if(string.IsNullOrEmpty(title) || string.IsNullOrEmpty(message))return;
        NotificationShow(title, message);
    }
}

public static class ViewOpera
{
    public static T? GetView<T>(StyledElement? control) where T : StyledElement
    {
        while (true)
        {
            if (control is null) return default;
            if (control is T t) return t;
            control = control.Parent;
        }
    }

    public static T? GetViewData<T>(StyledElement? control) where T : class
    {
        while (true)
        {
            if (control is null) return default;
            if (control.DataContext is T t) return t;
            control = control.Parent;
        }
    }
}